package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.MemberBalanceOperate;
import cn.wolfcode.crm.mapper.MemberBalanceOperateMapper;
import cn.wolfcode.crm.mapper.MemberMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IMemberBalanceOperateService;
import cn.wolfcode.crm.util.LogicException;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MemberBalanceOperateServiceImpl implements IMemberBalanceOperateService {
    @Autowired
    public MemberBalanceOperateMapper mapper;
    @Autowired
    public MemberMapper memberMapper;


    public void save(MemberBalanceOperate entity) {

        //计算得出操作后金额
        if(entity.getOperateType() == 0){
            entity.setBeginMoney(entity.getMember().getBalance());
            entity.setEndMoney(entity.getMember().getBalance().add(entity.getMoney()).add(entity.getSendMoney()));
        }else{
            entity.setBeginMoney(entity.getMember().getBalance());
            entity.setEndMoney(entity.getMember().getBalance().subtract(entity.getMoney()).subtract(entity.getSendMoney()));
        }
        //获取当前操作时间
        entity.setOperateDate(new Date());
        //操作人
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        entity.setEmployee(employee);
        //修改会员表已有的金额
        if( memberMapper.updateBalance(entity.getMember().getId(),entity.getEndMoney())!=1){
            throw new LogicException("商品扣费失败失败");
        }
        if(mapper.insert(entity) != 1){
            throw new LogicException("商品扣费失败失败");
        }
    }

    public PageResult queryPage(QueryObject qo) {
        PageResult pr = new PageResult();
        int total = mapper.queryForCount(qo);
        if (total == 0) {
            return pr;
        }
        List<MemberBalanceOperate> rows = mapper.queryForList(qo);
        pr.setTotal(total);
        pr.setRows(rows);
        return pr;
    }
}
